package 第二周.第四课;

/*
 * @author  YxinMiracle
 * @date  2022-04-26 15:44
 * @Gitee: https://gitee.com/yxinmiracle
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class 三数之和 {

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            List<List<Integer>> lists = twpSum(nums, -nums[i], i+1);
            if (lists.size() > 0){
                // 如果返回的数据有值
                for (List<Integer> list : lists) {
                    List<Integer> l = new ArrayList<>();
                    l.add(nums[i]);
                    l.add(list.get(0));
                    l.add(list.get(1));
                    result.add(l);
                }
            }
        }
        return result;
    }

    /**
     *
     * @param nums
     * @param target
     * @param index 在index的后面寻找答案
     * @return
     */
    public List<List<Integer>> twpSum(int[] nums, int target, int index) {
        List<List<Integer>> twoSumResult = new ArrayList<>();
        int j = nums.length - 1;
        for (int i = index; i < nums.length; i++) {
            if (i > index && nums[i] == nums[i - 1]) continue;
            while (i < j && nums[i] + nums[j] > target) j--;
            if (i < j && nums[i] + nums[j] == target) {
                List<Integer> list = new ArrayList<>();
                list.add(nums[i]);
                list.add(nums[j]);
                twoSumResult.add(list);
            }
        }
        return twoSumResult;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{0,0,0,0};
        System.out.println(new 三数之和().threeSum(nums));
    }

}
